/*
 * LdapDAO.java
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */
package com.gammapeit.customjaas.database;

import com.gammapeit.customjaas.constantes.ConstantesLdap;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

/**
 *
 * @author jlperea
 */
public class LdapDAO {

    protected static LdapDAO instance;
    ConstantesLdap ldapKtes = ConstantesLdap.getInstance();

    /**
     * Creates a new instance of LdapDAO
     */
    protected LdapDAO() {
    }

    public static LdapDAO getInstance() {
        if (instance == null) {
            instance = new LdapDAO();
        }
        return instance;
    }

    public boolean isloginCorrect(String username, String password) {
        Hashtable environmentHashtable = new Hashtable();
        environmentHashtable.put(Context.INITIAL_CONTEXT_FACTORY, ldapKtes.LDAP_INITIAL_CONTEXT_FACTORY);
        environmentHashtable.put(Context.PROVIDER_URL, ldapKtes.LDAP_URL_SERVER_NAME);
        environmentHashtable.put(Context.SECURITY_AUTHENTICATION, ldapKtes.LDAP_SECURITY_AUNTHENTICATION);
//        environmentHashtable.put(Context.SECURITY_PRINCIPAL, ldapKtes.LDAP_SECURITY_PRINCIPAL_PREFIX + username + "," + ldapKtes.LDAP_PEOPLE_SID);
//        environmentHashtable.put(Context.SECURITY_PRINCIPAL, "samAccountName=" + "m.ruiz" + "," + "dc=gammapeit,dc=com");
//        environmentHashtable.put(Context.SECURITY_CREDENTIALS, "Fake1234");

        boolean success = true;
        try {
            DirContext dirContext = new InitialDirContext(environmentHashtable);
            dirContext.close();
        } catch (NamingException e) {
            success = false;
            System.out.println("LdapDAO:isloginCorrect: failed login for " + username + ": " + e.toString());
        }
        return success;
    }

    public boolean loginCorrect(String username, String password) {
        NamingEnumeration<?> namingEnum = null;
        Hashtable env = new Hashtable(11);

        env.put(Context.INITIAL_CONTEXT_FACTORY, ldapKtes.LDAP_INITIAL_CONTEXT_FACTORY);
        env.put(Context.PROVIDER_URL, ldapKtes.LDAP_URL_SERVER_NAME);
        env.put(Context.SECURITY_AUTHENTICATION, ldapKtes.LDAP_SECURITY_AUNTHENTICATION);
        env.put(Context.SECURITY_PRINCIPAL, ldapKtes.LDAP_SECURITY_PRINCIPAL_PREFIX + ldapKtes.LDAP_USER + "," + ldapKtes.LDAP_PEOPLE_SID);
        env.put(Context.SECURITY_CREDENTIALS, ldapKtes.LDAP_PASSWORD);

        try {
            LdapContext ctx = new InitialLdapContext(env, null);
            ctx.setRequestControls(null);
            namingEnum = ctx.search("", "(&(objectCategory=user)(sAMAccountName=" + username + "))", getSimpleSearchControls());
            while (namingEnum.hasMore()) {
                SearchResult result = (SearchResult) namingEnum.next();
                Attributes attrs = result.getAttributes();
                Attribute dnAttr = attrs.get("distinguishedName");
                String dn = (String) dnAttr.get();

                env.put(Context.SECURITY_PRINCIPAL, dn);
                env.put(Context.SECURITY_CREDENTIALS, password);

                new InitialDirContext(env);
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if(namingEnum != null){
                    namingEnum.close();
                }
            } catch (NamingException ex) {
                Logger.getLogger(LdapDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return true;
    }

    private SearchControls getSimpleSearchControls() {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchControls.setTimeLimit(30000);
        return searchControls;
    }

//    public static void main(String[] a) {
//        try {
//            LdapDAO dao = LdapDAO.getInstance();
//
//            dao.loginCorrect("m.ruiz", "Fake1234");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}